<template>
  <div v-show="!isMain && !isView" class="add-equip-detail">
    <px-scrollbar class="add-equip-content">
      <px-button style="margin-top: 16px; margin-bottom: -4px" type="primary" icon="ArrowLeft" @click="backMainPage">返回</px-button>
      <EditDropDown dropdownTitle="盘点基本信息">
        <template v-slot:content>
          <px-form ref="formRef" :inline="true" :model="formValue" :rules="rules" label-position="right" label-width="120px">
            <px-row>
              <px-col :span="12">
                <px-form-item label="盘点组名称" prop="groupName">
                  <px-input v-model="formValue.groupName" placeholder="请输入盘点组名称" maxlength="50" clearable />
                </px-form-item>
              </px-col>
              <px-col :span="12">
                <EquipClassSelect :isRequired="true" :className="formValue.className" @changeClassName="changeClassName" />
              </px-col>
              <px-col :span="24">
                <px-form-item label="备注" prop="remark">
                  <px-input
                    v-model="formValue.remark"
                    type="textarea"
                    placeholder="请输入备注"
                    :autosize="{ minRows: 2, maxRows: 4 }"
                    maxlength="1000"
                  />
                </px-form-item>
              </px-col>
            </px-row>
          </px-form>
        </template>
      </EditDropDown>
      <EditDropDown dropdownTitle="工具盘点列表">
        <template v-slot:content>
          <px-button type="primary" style="margin-bottom: 16px" @click="dialogVisible = true">选择工具</px-button>
          <px-table :data="formValue.toolInfoDTOList" class="equip-table" size="small" max-height="300" border>
            <px-table-column prop="toolCode" label="工具编码" min-width="160" show-overflow-tooltip />
            <px-table-column prop="toolName" label="工具名称" min-width="160" show-overflow-tooltip />
            <px-table-column prop="toolStatusDesc" label="工具状态" min-width="120" show-overflow-tooltip>
              <template #default="scope">
                <px-tag
                  effect="plain"
                  :style="{
                    color: 'rgba(0, 0, 0, 0.8)',
                    border: `1px solid ${tagBorderColorList[scope.row.toolStatus]}`,
                    backgroundColor: `${tagBgColorList[scope.row.toolStatus]}`
                  }"
                >
                  {{ scope.row.toolStatusDesc }}
                </px-tag>
              </template>
            </px-table-column>
            <px-table-column prop="toolCategoryDesc" label="工具分类" min-width="100" show-overflow-tooltip />
            <px-table-column prop="toolUnitDesc" label="工具单位" min-width="100" show-overflow-tooltip />
            <px-table-column prop="toolModel" label="型号/规格" min-width="120" show-overflow-tooltip />
            <px-table-column prop="brandVal" label="品牌" min-width="120" show-overflow-tooltip />
            <px-table-column prop="toolPosition" label="工具位置" min-width="160" show-overflow-tooltip />
            <px-table-column fixed="right" label="操作" min-width="64" align="center">
              <template #default="scope">
                <px-tooltip content="删除" placement="top">
                  <px-button link type="danger" icon="Delete" @click="handleDeleteTool(scope.$index)" />
                </px-tooltip>
              </template>
            </px-table-column>
          </px-table>
        </template>
      </EditDropDown>
    </px-scrollbar>
    <div class="info-form-btns">
      <px-button @click="backMainPage">取消</px-button>
      <px-button type="primary" @click="handleSubmit(formRef)">保存</px-button>
    </div>
  </div>
  <!-- 选择备件弹窗 -->
  <AddSparePartsDialog :visible="dialogVisible" @closeDialog="closeDialog" @addTableRow="addTableRow" />
</template>
<script setup lang="ts">
import { addToolGroup, editToolGroup, getToolGroup } from "@/api/equip/toolManage";
import EditDropDown from "@/views/all/equip/components/EditDropDown.vue";
import EquipClassSelect from "@/views/all/equip/components/EquipClassSelect.vue";
import { PxMessage } from "px-ui";
import { computed, reactive, ref, toRefs, watch } from "vue";
import AddSparePartsDialog from "../../inventory/components/AddSparePartsDialog.vue";

// 调用父级-返回主页、查询列表方法
const emits = defineEmits(["backMainPage", "queryTable"]);
// 父级传过来的值
const props = defineProps(["isMain", "isView", "drawerType", "groupId"]);

// 显示隐藏
const isMain = computed(() => props.isMain);
const isView = computed(() => props.isView);

// 页面本身的值
const formRef = ref();
const state = reactive<any>({
  formValue: {},
  dialogVisible: false
});
const { formValue, dialogVisible } = toRefs(state);

const tagBorderColorList = {
  0: "#4CCBA1",
  1: "#F37272",
  2: "#F7B648",
  3: "#7997A8"
};

const tagBgColorList = {
  0: "#E8F8F3",
  1: "#FEECEC",
  2: "#FEF5E6",
  3: "#F7F7F7"
};

// 表单校验规则
const rules = computed(() => ({
  groupName: [{ required: true, message: "盘点名称不能为空", trigger: "blur" }]
}));

const handleDeleteTool = index => {
  formValue.value.toolInfoDTOList.splice(index, 1);
};

// 监视isMain和isView值
watch(isMain, async val => {
  if (!val && !props.isView) {
    formRef.value.resetFields();
    if (props.drawerType === "add") {
      formValue.value.groupName = "";
      formValue.value.className = "";
      formValue.value.remark = "";
      formValue.value.toolInfoDTOList = [];
    } else if (props.drawerType === "edit") {
      getDetail();
    }
  } else {
    formValue.value = {
      groupName: "",
      className: "",
      remark: "",
      toolInfoDTOList: []
    };
  }
});

// 获取详情接口
const getDetail = async () => {
  formValue.value = await getToolGroup(props.groupId);
};
// 返回主页面
const backMainPage = () => {
  formRef.value.resetFields();
  emits("backMainPage");
};
// 关闭子级dialog弹窗
const closeDialog = () => {
  dialogVisible.value = false;
};
// 选择备件后添加表格数据
const addTableRow = val => {
  formValue.value.toolInfoDTOList = formValue.value.toolInfoDTOList?.concat(val)?.filter((obj, index, self) => {
    return self.map(x => x.id).indexOf(obj.id) === index;
  });
};
// 提交
const handleSubmit = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      if (formValue.value.toolInfoDTOList && formValue.value.toolInfoDTOList.length > 0) {
        const arr = [];
        formValue.value.toolInfoDTOList.forEach(item => {
          arr.push(item.id);
        });
        const params = { toolIds: arr, ...formValue.value };
        if (props.drawerType === "add") {
          await addToolGroup(params);
          PxMessage.success("创建成功");
          emits("backMainPage");
          emits("queryTable");
        } else if (props.drawerType === "edit") {
          await editToolGroup(params);
          PxMessage.success("编辑成功");
          emits("backMainPage");
          emits("queryTable");
        }
      } else {
        PxMessage.error("工具列表不能为空");
      }
    }
  });
};

// 外部封装好的组件
// 科室组件调用父组件
const changeClassName = val => {
  formValue.value.className = val;
};
</script>
<style lang="scss" scoped>
@import url("@/views/all/equip/scss/add-detail.scss");
</style>
